<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import { getFileType } from '@/utils/common'
	import { uploadFile } from '@/api/login'
	import { getOrder, addOrderSales} from '@/api/shop'
	
	const loading = ref(false)
	const uForm = ref(null)
	const form = ref({
		orderId: '',
		status: 1,
		type: '',
		reason: undefined,
		payAmount: 0,
		description: '',
		images: [],
		list: [],
	})
	const rules = ref({
		reason: [
			{required: true, message: '请选择退款原因', trigger: ['blur', 'change']}
		],
		description: [
			{required: true, message: '请输入问题描述', trigger: 'blur'}
		],
		images: [
			{type: 'array', required: true, message: '请上传凭证', trigger: 'change'}
		]
	})
	const reasonList = ['包装破损', '商品质量问题', '发错货', '商品与描述不符', '其他']
	const reasonTypeList = ['CLOSED', 'ORDERED', 'PAID', 'SHIPPED', 'DELIVERED']
	
	function getData(id) {
		loading.value = true
		getOrder(id).then(res => {
			let result = res.result || {images: []}
			result.list.forEach(item => item.expand = false)
			form.value.orderId = result.orderId
			form.value.status = result.status
			form.value.saleStatus = result.saleStatus
			form.value.type = result.type
			form.value.payAmount = result.payAmount
			form.value.list = result.list
			loading.value = false
		}).catch(() => loading.value = false)
	}
	function statusToText(value) {
		switch(value) {
			case 0: return '已关闭';
			case 1: return '待付押金';
			case 2: return '待受理';
			case 3: return '待分拣';
			case 4: return '待出库';
			case 5: return '待发货';
			case 6: return '待收货';
			case 7: return '待确认';
			case 8: return '待付尾款';
			case 9: return '已完成';
			default: return '未知'
		}
	}
	function salesToText(value) {
		switch(value) {
			case 1: return '售后中';
			case 2: return '售后通过';
			case 3: return '售后驳回';
			default: return '未知'
		}
	}
	function changeDetailExpand(item) {
		item.expand = !item.expand
	}
	function reasonChange(e) {
		let index = e.detail.value
		form.value.reason = index
	}
	function chooseImg() {
		let typeList = ['png', 'jpg']
		uni.chooseImage({
			count: Math.abs(3 - Number(form.value.images.length)),
			sourceType: ['album', 'camera'], // 可以选择相册或相机
			success: async res => {
				let list = res.tempFiles
				let errType = list.some(file => !typeList.includes(getFileType(file.path)))
				if (errType) {
					uni.showToast({icon: 'none', title: '请上传图片格式为png/jpg'})
					return
				}
				let moreSize = list.some(file => file.size > 5242880)
				if (moreSize) {
					uni.showToast({icon: 'none', title: '上传图片大小不能超过5M'})
					return
				}
				loading.value = true
				for (let i = 0; i < list.length; i++) {
					try {
						const result = await uploadFile({filename: '售后凭证', filePath: list[i].path})
						form.value.images.push(result.result)
					} catch (e) {}
				}
				uForm.value.validateField('images')
				loading.value = false
			}
		})
	}
	function removeImg(index){
		form.value.images.splice(index, 1)
		uForm.value.validateField('images')
	}
	function viewImg(index) {
		let urls = form.value.images.map(item => item.furl)
		uni.previewImage({
			current: index,
			urls
		})
	}
	function submit() {
		uForm.value.validate().then(() => {
			loading.value = true
			let data = {
				orderId: form.value.orderId,
				reason: reasonTypeList[form.value.reason],
				description: form.value.description,
				images: form.value.images,
			}
			addOrderSales(data).then(res => {
				loading.value = false
				uni.showToast({icon: 'success', title: '申请成功'})
				setTimeout(()=>{
					uni.redirectTo({url: '/pages/shop/orderSalesSuccess'})
				}, 200)
			}).catch(() => loading.value = false)
		})
	}
	
	onLoad((option) => {
		let id = option.id
		if(id) getData(id)
	})
</script>

<template>
	<view class="app-container">
		<view class="app-content">
			<view class="content-top">
				<view class="goods-box">
					<view class="top-title">退款商品</view>
					<view v-for="item in form.list" :key="item.itemId" class="good-box">
						<goods v-model="item.num" :img="item.image && item.image.furl" :name="item.name" :price="item.price" :total="item.subtotal" 
							:specs="item.specs" :mode="form.type === 'INTEGRAL'? 'viewPL' : 'view'"></goods>
						<view class="goods-detail" v-if="item.type === 'DISHES' || item.type === 'DEVICE'">
							<template v-if="item.children && item.children.length">
								<view class="goods-detail-box" v-if="item.expand">
									<view class="goods-detail-item" v-for="child in item.children" :key="child.id">
										<goods v-model="child.number" :img="child.furl" :name="child.name" :price="child.price" :specs="child.specs" mode="viewD"
											v-if="child.name"></goods>
										<goods v-model="child.num" mode="invalidD" v-else></goods>
									</view>
								</view>
							</template>
							<view class="goods-detail-expand" @click="changeDetailExpand(item)">
								<text class="more-text">{{ item.expand? '收起' : '查看明细详情'}}</text>
								<uv-icon :name="item.expand? 'arrow-up-fill' : 'arrow-down-fill'" color="#4E5969" size="24"></uv-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="tip-box">
					<uv-icon name="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-25/1740473875950_safe-icon-primary.png" 
						size="30" />
					<text>平台报价 · 48小时质量无忧 · 极速退款</text>
				</view>
			</view>
			<uv-form :model="form" :rules="rules" ref="uForm" labelWidth="auto">
				<view class="form-box">
					<uv-form-item label="商品状态" required>
						<view class="custom-content">
							<text class="text-disable">{{form.saleStatus? salesToText(form.saleStatus) : statusToText(form.status)}}</text>
						</view>
					</uv-form-item>
				</view>
				<view class="form-box">
					<uv-form-item label="退款原因" prop="reason" required>
						<picker @change="reasonChange" :value="form.reason" :range="reasonList">
							<view class="custom-content">
								<text :class="form.reason === undefined? 'text-no' : ''">{{form.reason === undefined? '请选择原因' : reasonList[form.reason]}}</text>
								<uv-icon name="arrow-right" color="#54504D" size="30" />
							</view>
						</picker>
					</uv-form-item>
					<view class="view-row" v-if="form.reason !== undefined">
						<view class="row-left">
							<view class="left-title">退款金额<text class="text-red">*</text></view>
							<view class="left-tip">
								<text v-if="form.type === 'INTEGRAL'">最多金额退{{form.payAmount || 0}}积分</text>
								<text v-else>最多金额退￥{{form.payAmount? form.payAmount.toFixed(2) : 0.00}}</text>
							</view>
						</view>
						<view class="row-right">
							<text v-if="form.type === 'INTEGRAL'">{{form.payAmount || 0}}积分</text>
							<text v-else>¥{{form.payAmount? form.payAmount.toFixed(2) : 0.00}}</text>
						</view>
					</view>
					<view class="view-box">
						<uv-icon name="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2025-02-25/1740473875950_safe-icon-primary.png" size="30" />
						<text>最终退款金额以客服审核结果为准，此处仅参考</text>
					</view>
				</view>
				<view class="form-box form-top">
					<uv-form-item label="问题描述" labelPosition="top" prop="description" required>
						<view class="top-box">
							<uv-textarea v-model="form.description" placeholder="详细描述问题, 有助于人工审核快速通过" count border="none" height="200"
								:custom-style="{background: '#F8F5F5'}"></uv-textarea>
						</view>
					</uv-form-item>
				</view>
				<view class="form-box form-top">
					<uv-form-item label="上传凭证" labelPosition="top" prop="images" required>
						<view class="image-title">必须上传1~3张凭证，文件不超过5M</view>
						<view class="image-box">
							<view class="image-item" v-for="(img, index) in form.images" :key="index">
								<uv-image :src="img && img.furl" width="144" height="144" @click="viewImg(index)"></uv-image>
								<view class="image-del" @click.stop="removeImg(index)">
									<uv-icon name="close" color="#FFFFFF" size="30" />
								</view>
							</view>
							<view class="image-item select" @click="chooseImg" v-if="form.images.length < 3">
								<uv-icon name="camera-fill" color="#767473" size="60" />
							</view>
						</view>
					</uv-form-item>
				</view>
			</uv-form>
		</view>
		<view class="app-bottom">
			<uv-button color="linear-gradient( 102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" text="提交申请" @click="submit" :disabled="loading"></uv-button>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		padding-bottom: 120rpx;
		.app-content{
			padding: 24rpx;
			.content-top{
				border-radius: 16rpx;
				overflow: hidden;
				.goods-box{
					padding: 24rpx;
					background-color: #FFFFFF;
					.top-title{
						padding-bottom: 16rpx;
						margin-bottom: 16rpx;
						border-bottom: 2rpx solid #F4F4F4;
						font-weight: 600;
						font-size: var(--theme-lg);
						line-height: var(--theme-lg-line);
					}
					.good-box + .good-box{
						border-top: 2rpx solid #F4F4F4;
					}
				}
				.goods-detail {
					border-top: 2rpx solid #EAEAEA;
					font-size: 28rpx;
					.goods-detail-box{
						padding: 16rpx 0;
						display: flex;
						flex-direction: column;
						gap: 16rpx;
					}
					.goods-detail-expand {
						padding-top: 16rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						gap: 20rpx;
						color: #767473;
					}
					.goods-detail-box + .goods-detail-expand{
						border-top: 2rpx solid #EAEAEA;
					}
				}
				.tip-box{
					padding: 16rpx;
					display: flex;
					align-items: center;
					gap: 6rpx;
					color: #FF662F;
					background: rgba(255,102,47,0.1);
				}
			}
			.form-box{
				margin: 24rpx 0;
				background-color: #fff;
				padding: 12rpx 24rpx;
				border-radius: 16rpx;
				.custom-content{
					display: flex;
					justify-content: flex-end;
					gap: 10rpx;
				}
				.text-disable{
					color: #c0c4cc;
				}
				.text-no{
					color: #808080;
				}
				::v-deep .uv-form-item__body__left__content__label{
					font-weight: 600;
				}
				::v-deep .uv-form-item__body__left__content__required{
					left: unset;
					right: -8rpx;
				}
				&.form-top{
					.top-box{
						margin-top: 24rpx;
					}
					::v-deep .uv-form-item__body__left__content__required{
						left: 116rpx;
					}
				}
				.view-row{
					padding: 32rpx 0;
					display: flex;
					align-items: center;
					.row-left{
						flex-shrink: 0;
						.left-title{
							font-size: 15px;
							font-weight: 600;
						}
						.left-tip{
							color: #808080;
						}
					}
					.row-right{
						flex: 1;
						text-align: right;
						color: #FD1024;
					}
				}
				.view-box{
					display: flex;
					align-items: center;
					gap: 6rpx;
					color: #FF662F;
				}
				.image-title{
					margin: 8rpx 0 24rpx;
					color: #ADB0BD;
					font-size: var(--theme-sm);
					line-height: var(--theme-sm-line);
				}
				.image-box{
					width: 100%;
					display: flex;
					gap: 36rpx;
					.image-item{
						width: 144rpx;
						height: 144rpx;
						border-radius: 8rpx;
						background-color: #F8F5F5;
						position: relative;
						.image-del{
							position: absolute;
							top: 0;
							right: 0;
							width: 36rpx;
							height: 36rpx;
							background-color: rgba(28,33,62,0.5);
							border-top-right-radius: 8rpx;
							display: flex;
							justify-content: center;
							align-items: center;
						}
						&.select{
							display: flex;
							justify-content: center;
							align-items: center;
						}
					}
				}
			}
		}
		.app-bottom{
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0rpx;
			height: 120rpx;
			padding: 16rpx 24rpx;
			background-color: #FFFFFF;
			border-top: 2rpx solid #D7DBE1;
		}
	}
</style>